const express = require('express')
const mongoose = require("mongoose")
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express()

app.use(cors()); // 允许所有来源的跨域请求
// const router = express.Router()
const schedule = require('node-schedule');

let rule = new schedule.RecurrenceRule()
/**每天的凌晨12点更新代码*/
rule.hour = 23
rule.minute = 59
rule.second = 59
/**启动任务*/
schedule.scheduleJob(rule, () => {
  console.log('代码更新了！');
})

// 获取ip地址
const getLocalIP = require('./utils/tools').getLocalIP
global.localIp = getLocalIP()

// token 数据库集合
const Tokens = require('./schemas/users').Tokens;
// res.end封装
const jsonParse = require('./lib/jsonParse')
// 引入 接口文件集合
const requestHandler = require('./handle')

// 引入 路由映射
const routeMap = require("./routes")

// 使用body-parser中间件
app.use(bodyParser.urlencoded({
    extended: false
}))
app.use(bodyParser.json())

// DB config
const db = require('./config/keys').mogoURL

// connect to mogodb
mongoose.connect(db).then(() => {
    console.log('连接成功')
}, (err) => {
    console.log(err)
})

const getHandler = (key) => {
    return requestHandler[key]
}

let response = ''

//拦截所以api接口设置头部信息（不能放底部，why？）
app.all('*', function (req, res, next) {
    //跨域
    res.header('Access-Control-Allow-Origin', '*');
    res.header("Access-Control-Allow-Headers", "Authorization, Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name");
    // //设置前端的这些ajax请求方法'GET,POST,PUT,HEAD,DELETE,OPTIONS'，都有权限调接口
    res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,HEAD,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Credentials', true);
    // console.log(req.url,'前端传进来的参数为===：',req.method == 'GET'?req.query:req.body)
    // console.log(req.url)
    response = res
    let method = req.method.toUpperCase()
    if ('OPTIONS' == method) {
        res.sendStatus(200)
    } else {
        let requestName = ''
        if ('POST' == method) {
            requestName = req.url.replace('/api', '')
        } else if ('GET' == method) {
            let arr = req.url.split('?')
            requestName = arr[0].replace('/api', '')
        }
        let route = routeMap[requestName] || {}
        let handler = getHandler(route.handler)
        if (typeof handler === 'function') {
            const authorization = req.headers['Authorization'] || req.headers['authorization']
            const token = authorization.replace('Bearer ', '');
            Tokens.findOneAndUpdate({
                token: token
            }, {
                $set: {
                    expiresDate: new Date(new Date().getTime() + (8 * 60 * 60 * 1000)),
                    expiresIn: 1000
                },
            }, {
                returnNewDocument: true
            })
            // .then(res => 
            //     // console.log(res, 88888)
            // )
            if (route.needVerify) {
                requestHandler.verifyLogin(req, res, handler)
            } else {
                handler(req, res)
            }
        } else {
            getHandler('noHandler')(req, res)
        }
        return
    }
});

process.on('unhandledRejection', error => {
    console.log('我帮你处理了', error.message);
    jsonParse.sendResult(response, -2002, error.message)
})

const port = process.env.port || 5210

app.listen(port, () => {
    console.log(`Server runing on port: ${global.localIp}:${port}`, )
})